package com.sky.task;

import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

@Component
@Slf4j
public class OrderTask {

    @Autowired
    private OrderMapper orderMapper;

    //处理订单超时
    @Scheduled(cron = "0 * * * * *")//每隔一分钟就进行一次
    //@Scheduled(cron = "1/5 * * * * ?")//五秒执行一次,测试用
    public void processTimeoutOrder()
    {
        //log.info("处理超时订单:{}",LocalDateTime.now());
        //逻辑就是根据订单的状态和下单时间找出超时的订单
        //select * from order where status = ? and order_time < (现在的时间-15分钟)
        LocalDateTime localDateTime = LocalDateTime.now().plusMinutes(-15);

        List<Orders> list =orderMapper.getByStatusAndOrderTimeLT(Orders.PENDING_PAYMENT,localDateTime);
        if(list.size()>0&& list!=null)
        {
            for ( Orders order: list) {
                order.setStatus(Orders.CANCELLED);
                order.setCancelTime(LocalDateTime.now());
                order.setCancelReason("订单超时,未支付");
                orderMapper.update(order);//更新订单状态
            }
        }

    }

    //处理一直在派送中的订单,每天凌晨一点的时候触发任务
    @Scheduled(cron = "0 0 1 * * ?")//每天凌晨一点触发一次
    //@Scheduled(cron = "0/5 * * * * ?")//五秒执行一次,测试用
    public void processDeliveryOrder()
    {
        log.info("处理派送中的订单:{}",LocalDateTime.now());
        LocalDateTime time = LocalDateTime.now().plusMinutes(-60);//当前时间凌晨一点 减去一个小时 就是12点的订单,也就是昨天的一直处于派送中的订单
        //根据时间和派送中的状态 进行修改成 完成状态
        List<Orders> list = orderMapper.getByStatusAndOrderTimeLT(Orders.DELIVERY_IN_PROGRESS, time);
        for (Orders order : list) {
            order.setStatus(Orders.COMPLETED);
            orderMapper.update(order);
        }

    }
}
